<template>
  <div class="video-page">
    <!-- 筛选区域 -->
     <div class="filter-container" v-if="!isSelectMode">
      <!-- 筛选按钮组 -->
      <div class="filter-buttons">
        <button 
          :class="{ active: currentFilter === 'all' }" 
          @click="setFilter('all')"
          class="btn"
        >
          全部
        </button>
        <button 
          :class="{ active: currentFilter === 'approved' }" 
          @click="setFilter('approved')"
          class="btn"
        >
          审核通过
        </button>
        <button 
          :class="{ active: currentFilter === 'pending' }" 
          @click="setFilter('pending')"
          class="btn"
        >
          待审核
        </button>
      </div>

      <div class="search-upload">
        <div class="search-container">
          <input 
            v-model="searchQuery" 
            placeholder="搜索视频名称" 
            class="search-input" 
          />
          <img 
            src="@/assets/picture/find.png" 
            @click="searchVideos" 
            alt="搜索" 
            class="search-icon"
          />
        </div>
        <button class="btn upload-btn" @click="selectFile">上传视频</button>
        <!-- 隐藏的文件选择器 -->
        <input 
          type="file" 
          ref="fileInput" 
          @change="handleFileChange" 
          accept=".mp4,.avi,.mov" 
          style="display: none" 
        />
      </div>
    </div>
  <div class="filter-container" v-else style="display: flex;justify-content: flex-end;">
        <div class="search-upload">
        <div class="search-container">
          <input 
            v-model="searchQuery" 
            placeholder="搜索视频名称" 
            class="search-input" 
          />
          <img 
            src="@/assets/picture/find.png" 
            @click="searchVideos" 
            alt="搜索" 
            class="search-icon"
          />
        </div>
        <button class="btn upload-btn" @click="selectFile">上传视频</button>
        <!-- 隐藏的文件选择器 -->
        <input 
          type="file" 
          ref="fileInput" 
          @change="handleFileChange" 
          accept=".mp4,.avi,.mov" 
          style="display: none" 
        />
      </div>
    </div>
    <!-- 视频列表 -->
    <div class="video-list">
      <div
        class="video-card"
        v-for="video in paginatedVideos"
        :key="video.resource_id"
        :data-id="video.resource_id"
        @click="handleSelect(video)"
      >
        <div class="video-cover-container" @click="openVideo(video.resource_url)">
          <img 
            :src="video.video_cover || defaultCover" 
            alt="视频封面" 
            class="video-cover" 
          />
          <img 
            src="@/assets/picture/play.png" 
            alt="播放" 
            class="play-icon" 
          />
        </div>
        <div class="video-info">
          <span v-if="!video.isEditing">{{ video.resource_name }}</span>
          <input 
            v-if="video.isEditing" 
            type="text" 
            v-model="video.newName" 
            @blur="confirmRename(video)"
            @keyup.enter="confirmRename(video)"
            class="rename-input"
            :ref="`renameInput_${video.resource_id}`"
          />
          <p>{{ formatDate(video.update_time) }}</p>
        </div>
        <div class="button-group">
          <button class="btn btn-rename" @click="startRenaming(video)">重命名</button>
          <button class="btn btn-delete" @click="confirmDelete(video.resource_id)">删除</button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button class="btn" @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>当前页: {{ currentPage }} / {{ totalPages }}</span>
      <button class="btn" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick,watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchVideosApi, apiDeleteVideo, apiRenameVideo, uploadVideoApi } from "@/services/api"; // 确保 API 函数名称和路径正确

export default {
  name: "T_VideosPage",
   props: {
    isSelectMode: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const router = useRouter();
    const videos = ref([]);
    const currentFilter = ref("all");
    const searchQuery = ref("");
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const fileInput = ref(null);
    const file = ref(null);
    const defaultCover = "https://via.placeholder.com/300x150?text=No+Cover";

    // 获取技术ID和令牌
    const getTechIdAndToken = () => {
      const techId = localStorage.getItem("id");
      const token = localStorage.getItem("token");
      return { techId, token };
    };
     const handleSelect = (video) => {
      const selectedVideo = {
        id: video.resource_id,
        name: video.resource_name,
        type: 'video',
        uploadTime: video.update_time,
        url: video.resource_url
      };
      context.emit('video-selected', selectedVideo);  // 使用 context.emit
    };

    // Fetch videos based on filter and search query
    const fetchVideos = () => {
 const { techId, token } = getTechIdAndToken(); // 将变量声明提到顶部
  if (!techId || !token) {
    console.error('用户未登录。重定向到登录页面。');
    router.push('/login');
    return;
  }

  let filterStatus = props.isSelectMode ? 1 : null;
  if (!props.isSelectMode) {
    // 移除重复的 filterStatus 声明
    if (currentFilter.value === "approved") {
      filterStatus = 1;
    } else if (currentFilter.value === "pending") {
      filterStatus = 0;
    }
  }

  fetchVideosApi(techId, filterStatus, searchQuery.value, token)
    .then((response) => {
          if (response.data.status === 1) {
            // 初始化每个视频的编辑状态和新名称
            videos.value = response.data.data.map(video => ({
              ...video,
              isEditing: false,
              newName: video.resource_name,
            }));
          } else {
            console.error('获取视频失败:', response.data.msg);
            if (response.data.status === 'NOT_LOGIN') {
              router.push('/login');
            }
          }
        })
        .catch(error => {
          console.error('请求错误:', error);
        });
          
    };
 watch(() => props.isSelectMode, (newVal) => {
      if(newVal) {
        currentFilter.value = 'approved';
        fetchVideos();
      }
    });
    const setFilter = (filter) => {
      currentFilter.value = filter;
      currentPage.value = 1;
      fetchVideos();
    };

    const searchVideos = () => {
      currentPage.value = 1;
      fetchVideos();
    };

    const selectFile = () => {
      if (fileInput.value) {
        fileInput.value.click();
      }
    };

    const handleFileChange = (event) => {
      const selectedFile = event.target.files[0];
      if (!selectedFile) {
        return;
      }
      file.value = selectedFile;
      uploadVideo();
    };

    const uploadVideo = () => {
      const { techId } = getTechIdAndToken();
      const formData = new FormData();
      formData.append('tech_id', techId);
      formData.append('resource_type', getFileType(file.value));
      formData.append('file', file.value);

      uploadVideoApi(formData)
        .then(response => {
          if (response.data.status === 1) {
            console.log('视频上传成功:', response.data);
            ElMessage.success('视频上传成功！');
            fetchVideos();
          } else {
            console.error('视频上传失败:', response.data.msg);
          }
        })
        .catch(error => {
          console.error('视频上传失败:', error);
          ElMessage.error('视频上传失败，请重试。');
        });
    };

    const getFileType = (file) => {
      const extension = file.name.split('.').pop().toLowerCase();
      if (['mp4', 'avi', 'mov'].includes(extension)) {
        return 'video';
      } else {
        return 'other';
      }
    };

    const filteredVideos = computed(() => {
      let filtered = videos.value;
  
  // 强制模式优先：选择模式下只显示审核通过
  if (props.isSelectMode) {
    filtered = filtered.filter(video => video.ispass === 1);
  } else {
    // 普通模式按筛选器过滤
    if (currentFilter.value === "approved") {
      filtered = filtered.filter(video => video.ispass === 1);
    } else if (currentFilter.value === "pending") {
      filtered = filtered.filter(video => video.ispass === 0);
    }
  }

  // 应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(video => 
      video.resource_name.toLowerCase().includes(query)
    );
  }

  return filtered;
    });

    const paginatedVideos = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredVideos.value.slice(start, end);
    });

    const totalPages = computed(() => Math.ceil(filteredVideos.value.length / itemsPerPage));

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    const startRenaming = (video) => {
      console.log('开始重命名视频:', video.resource_id); // 调试日志

      // 取消其他视频的编辑状态
      videos.value.forEach(v => {
        if (v.resource_id !== video.resource_id) {
          v.isEditing = false;
        }
      });

      video.isEditing = true;
      video.newName = video.resource_name;

      // 手动聚焦输入框
      nextTick(() => {
        const input = refs[`renameInput_${video.resource_id}`];
        if (input) input.focus();
      });
    };

    const confirmRename = (video) => {
      console.log('确认重命名视频:', video.resource_id, '新名称:', video.newName); // 调试日志

      if (video.newName.trim() && video.newName !== video.resource_name) {
        apiRenameVideo(video.resource_id, video.newName)
          .then(response => {
            if (response.data.status === 1) {
              video.resource_name = video.newName;
              ElMessage.success('重命名成功！');
            } else {
              console.error('重命名失败:', response.data.msg);
              ElMessage.error('重命名失败，请重试。');
            }
          })
          .catch(error => {
            console.error('重命名请求错误:', error);
            ElMessage.error('重命名失败，请检查网络或稍后重试。');
          });
      }
      video.isEditing = false;
    };

    const confirmDelete = async (videoId) => {
      try {
        await ElMessageBox.confirm(
          '此操作将永久删除该视频，是否继续？',
          '警告',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        const response = await apiDeleteVideo(videoId);
        if (response.data.status === 1) {
          ElMessage.success("删除成功！");
          videos.value = videos.value.filter(video => video.resource_id !== videoId);
        } else {
          console.error('删除失败:', response.data.msg);
          ElMessage.error('删除失败，请重试。');
        }
      } catch (error) {
        // 用户取消删除操作自动捕获，无需处理
      }
    };

    const openVideo = (videoUrl) => {
      window.open(videoUrl, "_blank");
    };

    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleString();
    };

    onMounted(() => {
      const { techId, token } = getTechIdAndToken();
      if (techId && token) {
        fetchVideos();
      } else {
        console.error('用户未登录。重定向到登录页面。');
        router.push('/login');
      }
    });

    // 创建一个 refs 对象，用于动态引用输入框
    const refs = {};
    const setupRefs = () => {
      const bind = (name) => (el) => {
        refs[name] = el;
      };
      return { bind };
    };

    const { bind } = setupRefs();

    return {
      videos,
      currentFilter,
      searchQuery,
      currentPage,
      paginatedVideos,
      totalPages,
      defaultCover,
      setFilter,
      fetchVideos,
      searchVideos,
      selectFile,
      handleFileChange,
      uploadVideo,
      confirmDelete,
      openVideo,
      startRenaming,
      confirmRename,
      formatDate,
      prevPage,
      nextPage,
      fileInput,
      bind, // 导出 bind 方法
      handleSelect
    };
  },
};
</script>

<style scoped>
.video-page[data-selectmode] .filter-buttons {
  display: none !important;
}
.video-page {
  padding: 20px;
  min-height: 70vh;
  display: flex;          /* 新增 */
  flex-direction: column; /* 新增 */
}
.search-container {
  position: relative;
  display: flex;
  align-items: center;
}
h1 {
  text-align: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-buttons .btn {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
  border-radius: 0px;
}

.filter-buttons .btn.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.search-upload {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px; /* 为搜索图标留出空间 */
  border-radius: 20px;
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.btn {
  padding: 8px 12px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  background-color: #e0e0e0;
  transition: background-color 0.3s;
}

.upload-btn {
  background-color: #125AA2;
  color: #fff;
}

.upload-btn:hover {
  background-color: #3987d4;
}

.btn-rename {
  background-color: #125AA2;
  font-size: 13px;
  color: #fff;
  padding: 6px 12px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-right: 5px; /* 确保按钮之间有间隔 */
}

.btn-rename:hover {
  background-color: #3987d4;
}

.btn-delete {
  background-color: #E85C5C;
  color: #fff;
  font-size: 13px;
  padding: 6px 12px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-delete:hover {
  background-color: #d32f2f;
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
}

.video-card {
  border: 1px solid #dddddd85; /* 修正边框语法 */
  border-radius: 5px;
  background-color: #fff;
  text-align: center;
  position: relative;
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.video-cover-container {
  position: relative;
  cursor: pointer; /* 更改鼠标为手型 */
}

.video-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0; /* 默认隐藏 */
  transition: opacity 0.3s ease; /* 平滑过渡 */
  width: 60px; /* 根据需要调整大小 */
  height: 60px;
  pointer-events: none; /* 允许点击事件传递到下方元素 */
}

.video-card:hover .play-icon {
  opacity: 0.9; /* 悬停时显示 */
}
.video-card:hover img {
  opacity: 0.9; 
}


.video-info {
  margin-top: 10px;
  /* cursor: pointer; */ /* 移除 cursor 以避免误导用户点击事件 */
}

.video-info span {
  display: block;
  font-size: 13px;
  font-weight: bold;
  margin: 0px 10px;
  color: #333333c9;
  white-space: nowrap;
  overflow: hidden;
}

.video-info p {
  margin-top: 5px;
  font-size: 10px;
  color: rgba(119, 119, 119, 0.863);
}

.rename-input {
  padding: 5px 8px;
  margin-top: 5px;
  border: 1px solid #2196f3;
  border-radius: 4px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin: 10px 0px 15px 0px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination .btn {
  padding: 8px 12px;
  cursor: pointer;
  border: none;
  background-color: #2196f3;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.pagination .btn:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.pagination .btn:not(:disabled):hover {
  background-color: #1976d2;
}

.pagination span {
  font-size: 16px;
  color: #333;
}
</style>
